"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

import re

#token type
TOKEN_TEXT = 0
TOKEN_VAR = 1
TOKEN_BLOCK = 2
TOKEN_TRANSLATE = 3 

#token_tag
BEGIN_BLOCK_TAG = '{%'
END_BLOCK_TAG = '%}'
BEGIN_VAR_TAG = '{{'
END_VAR_TAG = '}}'
BEGIN_TRANSLATE_TAG = '_('
END_TRANSLATE_TAG = ')'
#
class Token:
        def __init__( self, type, value ):
                self.type = type
                self.value = value
                
        def __str__( self ):
                self.toStr()
                        
        def toStr( self ):
                str = ''
                if self.type == TOKEN_TEXT:
                        str = '<text>' + self.value + '\n</text>'
                elif self.type == TOKEN_VAR:
                        str = '<var>' + self.value + '\n</var>'
                else:
                        str = '<block>' + self.value + '\n</block>'
                return str

        
def createToken( token_string ):
        if token_string.startswith( BEGIN_BLOCK_TAG ):
                return Token( TOKEN_BLOCK, token_string[ len( BEGIN_BLOCK_TAG ) : -len( END_BLOCK_TAG ) ] )
        elif token_string.startswith( BEGIN_VAR_TAG ):
                return Token( TOKEN_VAR, token_string[ len( BEGIN_VAR_TAG ) : -len( END_VAR_TAG ) ])
        elif token_string.startswith( BEGIN_TRANSLATE_TAG ):
                return Token( TOKEN_TRANSLATE, token_string[ len( BEGIN_TRANSLATE_TAG ) : -len( END_TRANSLATE_TAG ) ])
        else:
                return Token( TOKEN_TEXT, token_string )

#separate token from org_string
def createTokenList( org_string ):
        tag_re = re.compile('(%s.*?%s|%s.*?%s|%s.*?%s)' % 
                                    (re.escape(BEGIN_BLOCK_TAG), 
                                    re.escape(END_BLOCK_TAG),
                                    re.escape(BEGIN_VAR_TAG), 
                                    re.escape(END_VAR_TAG),
                                    re.escape(BEGIN_TRANSLATE_TAG), 
                                    re.escape(END_TRANSLATE_TAG)
                                    ))
        elements = filter( None,tag_re.split( org_string ) )
        token_list = map( createToken, elements )
        return token_list
